package mq.demo.simple;

import cn.itlaobing.Util.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;

/**
 * @author mifei
 * @create 2018年04月12日
 **/
public class Recv {
    private final static String QUEUE_NAME = "mq_test_simple";

    public static void main(String[] argv) throws Exception {

        // 获取连接
        Connection connection = ConnectionUtil.getConnection();
        // 创建通道
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 定义队列的消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 监听队列
        channel.basicConsume(QUEUE_NAME, false, consumer);  //手动确认

        int i=0;
        // 获取消息
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery(); //阻塞或轮询
            String message = new String(delivery.getBody());
            if (message.indexOf("2")>0){
                i++;
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
            System.out.println(i+"获取:" + message);
        }
    }
}
